﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kevin.Comm.Utility;
using Kevin.Shop.Business.Core.Components;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Core.Components.Sales;
using Kevin.Shop.Business.Core.Member;
using Kevin.Shop.Business.SalesManagement.Components.Order;
using Kevin.Shop.Business.Service.Entity.Helper;
using Kevin.Shop.Business.Service.Entity.SalesManagement.Shipping;
using Kevin.Shop.Business.Shopping.Components;
using RiderShop.Mobile.Common.Component;
using RiderShop.Mobile.ServiceEntity.Purchase;
using Kevin.Shop.Business.Service.Entity.SalesManagement.PromotionCode;

namespace RiderShop.Mobile.Modle.Purchase
{
    public class CheckOutModel
    {
        private List<UserShipingAddress> _userShipingAddresses;
        private ServiceResponser _orderResult = new ServiceResponser();

        /// <summary>
        /// 用户行为
        /// </summary>
        public string Behaviour { get; set; }

        private ShoppingCartInfo _cartInfo;
        public ShoppingCartInfo CartInfo
        {
            get
            {
                if (_cartInfo == null || _cartInfo.ProductList == null || _cartInfo.ProductList.Count == 0)
                {
                    _cartInfo = ShippingCartModel.BuildShoppingCartPro();
                }
                return _cartInfo;
            }
        }

        public List<OrderShippingType> OrderShippingType
        {
            get { return GetOrderShippingType(); }
        }

        public List<OrderPaymentType> OrderPaymentType
        {
            get { return GetOrderPaymentType(); }
        }

        public List<PromotionCodeCustomerEntity> PromotionCodeList
        {
            get { return GetPromotionCodeList(); }
        }

        public int UserCurrentPoint
        {
            get
            {
                var user = WebClientContext.Current.GetCurrentUser(false);
                return user != null ? user.Points : 0;
            }
        }

        public string OrderInfoJson
        {
            get
            {
                return Serializer.ConvertObjectToJson(new OrderBasicInfo());
            }
        }

        public List<UserShipingAddress> UserShipingAddresses
        {
            get
            {
                if (_userShipingAddresses == null)
                {
                    GetUserShippingAddress(WebClientContext.Current.UserId);
                }
                return _userShipingAddresses;
            }
            set { _userShipingAddresses = value; }
        }

        public UserShipingAddress DefaultShipingAddresses
        {
            get { return UserShipingAddresses.FirstOrDefault(p => p.IsDefault != null && (p.IsDefault.Value || !string.IsNullOrEmpty(p.Address))); }
        }

        public List<UserShipingAddress> AllShipingAddresses
        {
            get { return UserShipingAddresses; }
        }

        public bool NeedAddShippingAddress
        {
            get { return UserShipingAddresses.Count == 0; }
        }

        public ServiceResponser OrderResult
        {
            get { return _orderResult; }
            set { _orderResult = value; }
        }

        public OrderBasicInfo CurrentOrder { get; set; }

        /// <summary>
        /// 获取配送信息列表
        /// </summary>
        /// <returns></returns>
        public static List<OrderShippingType> GetOrderShippingType()
        {
            var list = KevinCache.Get(CookieKeys.CookieKeysOrderShippingType) as List<OrderShippingType>;
            if (list == null)
            {
                list = RestfulHelper.Query<OrderShippingType>(SiteUrl.FormatUrl("SalesManagement_OrderShippingType"));
                KevinCache.Insert(CookieKeys.CookieKeysOrderShippingType, list);
            }

            return list;
        }

        /// <summary>
        /// 获取支付信息列表
        /// </summary>
        /// <returns></returns>
        public static List<OrderPaymentType> GetOrderPaymentType()
        {
            var result = RestfulHelper.Query<OrderPaymentType>(SiteUrl.FormatUrl("SalesManagement_OrderPaymentType"));
            return result;
        }

        /// <summary>
        /// 获取当前订单可用promotion Code
        /// </summary>
        /// <returns></returns>
        public static List<PromotionCodeCustomerEntity> GetPromotionCodeList()
        {
            var order = new OrderBasicInfo();
            order.CustomerUserId = WebClientContext.Current.UserId;
            var productList = ShoppingCartHelper.BuidShoppCartForCookie();
            foreach (var item in productList)
            {
                var orderProduct = new OrderProductInfo()
                {
                    ProductId = item.ProductId,
                    Quantity = item.Quantity
                };
                order.ProductList.Add(orderProduct);
            }

            var result = RestfulHelper.QueryWithSingle<PromotionCodeEntity>(SiteUrl.FormatUrl("SalesManagement_GetUserPromotionCodeForOrder"), order);
            List<PromotionCodeCustomerEntity> list = null;
            if (result != null)
            {
                list = result.PromotionCodeCustomerList;
            }

            return list ?? new List<PromotionCodeCustomerEntity>();

        }

        public List<UserShipingAddress> GetUserShippingAddress(int userId, int shippingId)
        {
            return RestfulHelper.Query<UserShipingAddress>(SiteUrl.FormatUrl("SalesManagement_GetUserShipingAddress", userId, shippingId));
        }

        public void GetUserShippingAddress(int userId)
        {
            _userShipingAddresses = RestfulHelper.Query<UserShipingAddress>(SiteUrl.FormatUrl("SalesManagement_GetUserShipingAddress", userId, 0));
        }

        public ServiceResponser SubmitOrder(OrderBasicInfo order)
        {
            //订单添加ProductList
            foreach (ShoppingCartItemInfo item in CartInfo.ProductList)
            {
                OrderProductInfo product = ShoppingCartHelper.GetOrderProductInfo(item);
                order.ProductList.Add(product);
            }
            //订单添加GiftCard
            var gcList = ShoppingCartHelper.ShoppingCartGiftCardList;
            gcList.ToList().ForEach(x => order.GiftCardList.Add(x));

            //Get Default User
            string authTokenuser = System.Configuration.ConfigurationManager.AppSettings["DefaultAuthUser"];
            string urlGetUser = SiteUrl.FormatUrl("Common_GetUserInfoByThirdId", authTokenuser);
            if (!string.IsNullOrEmpty(urlGetUser))
            {
                var userList = RestfulHelper.Query<UserBasicInfo>(urlGetUser);
                if (userList.Count > 0)
                {
                    order.InUser = userList[0].UserId;
                    order.CurrentUserId = WebClientContext.Current.UserId;
                }
            }
            //用户信息
            order.InUser = WebClientContext.Current.UserId;
            order.CustomerUserId = WebClientContext.Current.UserId;

            //配送方式和支付方式信息
            var ostypes = GetOrderShippingType();

            //如果只是积分支付
            if (WebClientContext.Current.OnLinePayment == PaymentType.PointPay)
            {
                GetUserShippingAddress(100);
                order.ShippingId = _userShipingAddresses.Count > 0 ? _userShipingAddresses[0].ShippingId : 0;
                order.ShippingModeId = ostypes.Count > 0 ? ostypes[0].ShippingModeId : 0;
                order.ShippingModeName = ostypes.Count > 0 ? ostypes[0].ShippingModeName : String.Empty;
            }
            else//普通支付方式
            {
                foreach (OrderShippingType item in ostypes)
                {
                    if (item.ShippingModeId == order.ShippingModeId)
                    {
                        order.ShippingModeName = item.ShippingModeName;
                        break;
                    }
                }
            }

            //金额信息
            var amountInfo = ShoppingCartHelper.ShoppingCartAmountInfo;
            order.OrderGiftCardAmount = amountInfo.GiftCardAmount;
            order.OrderExpenseAmount = amountInfo.ExpenseAmount;
            order.OrderTotalAmount = CartInfo.TotalAmount;
            order.ShippingCharge = CartInfo.ShippingCharge;
            order.DiscountAmount = CartInfo.DiscountAmount;

            var response = RestfulHelper.Update(SiteUrl.FormatUrl("SalesManagement_CreateOrderByApp"), order);
            if (response.Status)
            {
                //有"-"代表不是微信卡卷，不需要核销
                if (!string.IsNullOrEmpty(order.PromotionCode) && !order.PromotionCode.Contains("-"))
                {
                    UseThirdPromotionCode(order.PromotionCode);
                }
                response.Tag = response.Tag.Trim() + "," + order.OrderPayAmount + "," + order.ArrivePay;
            }
            OrderResult = response;
            return response;
        }

        public void UseThirdPromotionCode(string code)
        {
            RiderShop.Mobile.Common.Component.OAuth.Weixing.WeixingOAuth.UsePromotionCode(code, string.Empty);
        }

        /// <summary>
        /// 计算购物车金额，包括促销
        /// </summary>
        public ShoppingCartAmountInfo OrderBalanceCompute(int shiptype, int shippingId, string promotionCode = "", int point = 0)
        {
            var order = new OrderBasicInfo();

            order.ShippingModeId = shiptype;
            order.ShippingId = shippingId;
            //本地送礼订单或外地送礼订单
            if (shippingId == -1 || shippingId == -2)
            {
                order.OrderType = 6;
            }
            order.CustomerUserId = WebClientContext.Current.UserId;
            order.PromotionCode = promotionCode;
            order.OrderExpensePoint = point;
            var productList = ShoppingCartHelper.BuidShoppCartForCookie();
            foreach (var item in productList)
            {
                var orderProduct = new OrderProductInfo()
                                       {
                                           ProductId = item.ProductId,
                                           Quantity = item.Quantity
                                       };
                order.ProductList.Add(orderProduct);
            }

            var amount = RestfulHelper.QueryWithSingle<ShoppingCartAmountInfo>(SiteUrl.FormatUrl("SalesManagement_Calculate"), order);

            return amount;
        }
    }
}
